#!/usr/bin/env bash

set -Eeuxo pipefail
source ./tasks/helpers.sh
source ./tasks/helpers/detect_os_release.sh

# shellcheck source=build/package_dependencies.sh
source "$SOURCE_DIR/build/package_dependencies.sh"

install_dependencies=("${all_build_dependencies[@]}")
if [ "${INSTALL_TEST_DEPENDENCIES:-}" == "true" ]; then
  install_dependencies=("${all_dependencies[@]}")
fi

detect_os_release
if [[ "$ID_NORMALIZED" == "rhel" && "$VERSION_ID" == "7" ]]; then
  # Dependencies for GCC 7+ for compiling TrafficServer (C++17 required).
  yum -y install centos-release-scl

  yum -y install "${install_dependencies[@]}"
  # Ensure the packages got installed, since yum's exit code isn't always
  # useful: http://stackoverflow.com/a/22393088
  rpm --query --queryformat "" "${install_dependencies[@]}"
elif [[ "$ID_NORMALIZED" == "debian" ]]; then
  # Dependencies for GCC 7+ or Clang 5+ for compiling TrafficServer (C++17
  # required).
  if [[ "$ID" == "debian" && "$VERSION_ID" == "9" ]]; then
    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get -y --no-install-recommends install curl ca-certificates gnupg
    curl -sS https://apt.llvm.org/llvm-snapshot.gpg.key | apt-key add -
    if [[ "$ID" == "debian" && "$VERSION_ID" == "8" ]]; then
      echo "deb http://apt.llvm.org/jessie/ llvm-toolchain-jessie-7 main" > /etc/apt/sources.list.d/api-umbrella-llvm.list
    else
      echo "deb http://apt.llvm.org/stretch/ llvm-toolchain-stretch-7 main" > /etc/apt/sources.list.d/api-umbrella-llvm.list
    fi
  fi

  apt-get update
  DEBIAN_FRONTEND=noninteractive apt-get -y --no-install-recommends install "${install_dependencies[@]}"
else
  echo "Unknown build system"
  exit 1
fi

if [ "${INSTALL_TEST_DEPENDENCIES:-}" == "true" ]; then
  if [ "$ID" == "debian" ]; then
    # Add Chromium for integration tests.
    apt-get update
    apt-get -y --no-install-recommends install chromium chromium-driver curl unzip
    chromium --version
    chromedriver --version
  fi
fi
